package com.loginlib.presenters;

import android.text.TextUtils;
import android.util.Log;

import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.google.gson.Gson;
import com.liulishuo.filedownloader.BaseDownloadTask;
import com.liulishuo.filedownloader.FileDownloadListener;
import com.loginlib.panel.InitPanel;
import com.orhanobut.logger.Logger;
import com.wanhe.base.BaseApplication;
import com.wanhe.base.Const;
import com.wanhe.base.model.base.Dish;
import com.wanhe.base.model.base.DishesType;
import com.wanhe.base.model.disgn.DSFile;
import com.wanhe.base.model.disgn.VideoModel;
import com.wanhe.base.model.entity.DesignEntity;
import com.wanhe.base.model.entity.DishesTypeDetailEntity;
import com.wanhe.base.model.entity.MenuDesignEntity;
import com.wanhe.base.model.entity.SellOutResultEntity;
import com.wanhe.base.model.holder.DishConfHolder;
import com.wanhe.base.model.holder.DishHolder;
import com.wanhe.base.model.holder.DishTypeHolder;
import com.wanhe.base.model.holder.FileHolder;
import com.wanhe.base.model.holder.VideoHolder;
import com.wanhe.base.net.ServerApi;
import com.wanhe.base.presents.BasePresenter;
import com.wanhe.base.runner.Runner;
import com.wanhe.base.util.FileDownLoadUtil;
import com.wanhe.base.util.ObjectUtil;
import com.wanhe.base.util.SPUtils;
import com.wanhe.base.util.StringFileUtil;
import com.wanhe.base.util.ViewUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;

import javax.inject.Inject;

import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Consumer;

/**
 * Created by yanchx on 2017/7/5.
 */

public class InitDataPresenter extends BasePresenter {

    public static final String TAG = "InitDataPresenter";
    Gson gson = new Gson();

    public void setInitPanel(InitPanel initPanel) {
        this.initPanel = initPanel;
    }

    private  InitPanel initPanel;

    @Inject
    public InitDataPresenter(ServerApi api, Runner runner) {
        super(api, runner);
    }

    public void getAllDish() {
        final boolean isExist = !TextUtils.isEmpty(SPUtils.getAllDish());
        runner.execute(api.getAllDish(), new Consumer<DishesTypeDetailEntity>() {
            @Override
            public void accept(@NonNull DishesTypeDetailEntity entity) throws Exception {
                if (entity.resultType != DishesTypeDetailEntity.SUCCESS) {
                    if (isExist) {
                        memCacheDishData(SPUtils.getAllDish());
                        if (initPanel != null) initPanel.onDishDataErrUseCacheData();
                    }else{
                        if (initPanel != null) initPanel.onInitDishDataFail();
                    }
                }else{
                  String data =   gson.toJson(entity);
                    Log.d("initData","data="+data);
                    SPUtils.setAllDish(data);
                    //转化菜品数据
                    memCacheDishData(gson.toJson(entity));
                    if(initPanel!=null) initPanel.onInitDishDataSuccess();
                }
            }
        },getError(1));
    }

    public void getSellOutData() {
        final boolean isExist = !TextUtils.isEmpty(SPUtils.getSallOutData());
        runner.execute(api.getSellOutData(), new Consumer<SellOutResultEntity>() {
            @Override
            public void accept(@NonNull SellOutResultEntity entity) throws Exception {
                if (entity.resultType != SellOutResultEntity.SUCCESS) {
                    if (isExist) {
                        if (initPanel != null) initPanel.onSallOutDataErrUseCache();
                    }else{
                        if (initPanel != null) initPanel.onSallOutDataInitFail();
                    }
                }else{
                    SPUtils.setSallOutData(gson.toJson(entity));
//                    //转化菜品数据
//                    memCacheDishData(gson.toJson(entity));
                    if(initPanel!=null) initPanel.onSallOutDataInitSuccess();
                }
            }
        },getError(3));
    }

    public void getDesignData() {
        final boolean isExist = !TextUtils.isEmpty(SPUtils.getDesign());
        runner.execute(api.getMenuDesignData(), new Consumer<MenuDesignEntity>() {
            @Override
            public void accept(@NonNull MenuDesignEntity entity) throws Exception {
                if (entity.resultType != MenuDesignEntity.SUCCESS) {
                    if (isExist) {
//                        memCacheDishData(SPUtils.getDesign());
                        //TODO 处理数据
                        if (initPanel != null) initPanel.onDesignDataErrUseCacheData();
                    }else{
                        if (initPanel != null) initPanel.onInitDesignDataFail();
                    }
                }else{
                    SPUtils.setDesign(entity.MenuData);
                    //下载图片
                    download(entity);
                }
            }
        },getError(2));
    }



    public void download( MenuDesignEntity entity){
        DesignEntity resultEntity = gson.fromJson(entity.MenuData, DesignEntity.class);
        if(entity==null||resultEntity==null){
            if (initPanel!=null) {
                initPanel.onLoadingDesignBGImageProcess(0, null);
            }
            return;
        }


        List<DesignEntity.DSFilesGroup> files = resultEntity.files;
        FileHolder instance = FileHolder.getInstance();
        /**
         * 将设计器缓存起来，用于后期的方便查找
         *
         * @author 陈德基
         * @time 2017/7/10 16:31
         */
        List<DSFile> dsFiles = new ArrayList<>();
        for (int i = 0; i < files.size(); i++) {
            DesignEntity.DSFilesGroup group = files.get(i);
            for (int j = 0; j < group.getFiles().size(); j++) {
                DSFile file = group.getFiles().get(j);
                instance.put(file.getFid(), file);
                dsFiles.add(file);
            }
        }

        downloadFiles(dsFiles);

//        List<DesignEntity.DSFilesGroup> catalogs=resultEntity.files;
//        List<PageViewModel> pageViewModels = new ArrayList<>();
//        for(DesignEntity.DSFilesGroup catalog:catalogs){
//
//            if(catalog!=null&&catalog.getPages()!=null&&catalog.getPages().size()>0){
//                pageViewModels.addAll(catalog.getPages());
//            }
//        }
        //Glide下载图片
//         int pageCount = pageViewModels.size();
//        if (ObjectUtil.checkObjectList(pageViewModels)) {
//            for (PageViewModel model : pageViewModels) {
//                FileHolder.getInstance();
//                Log.d("initData","imageUrl="+Const.getMenuDataImage());
//                Glide.with(BaseApplication.context).load().downloadOnly(new InitLoadingSimpleTarget(pageCount));
////                if (initPanel!=null) {
////                    initPanel.onLoadingDesignBGImageProcess(pageCount,null);
////                }
//            }
//        }
    }

    private void downloadFiles(List<DSFile> dsFiles) {
        /**
         * 调用下载接口下载文件
         * @author 陈德基
         * @time 2017/7/20 17:13
         */
        List<String> localFilePathes = new ArrayList<>();
        List<String> fileNames = new ArrayList<>();
        for (int i = 0; i < dsFiles.size(); i++) {
            String fileName = dsFiles.get(i).getFileName();
            fileNames.add(fileName);
            String basePath = null;
            if (fileName.endsWith("jpg")
                    || fileName.endsWith("png")){
                basePath = Const.imageBaseUrl;
            } else if (fileName.endsWith("mp4")){
                basePath = Const.videoBaseUrl;
            } else if (fileName.endsWith("gif")){
                basePath = Const.gifBaseUrl;
            }
            String localFilePath = basePath + fileName;
            localFilePathes.add(localFilePath);
        }

//        Const.getMenuDataImage(model.getImage().getFileName())
        String baseUrl = Const.getHostAddress() + Const.GET_IMAGE + "/menu_image/";

        FileDownLoadUtil.downloaderList(baseUrl, fileNames, localFilePathes, new PadFilesDownloadListener(dsFiles.size()));



    }

    private class PadFilesDownloadListener extends FileDownloadListener{

        private final int mCount;

        public PadFilesDownloadListener(int count){
            this.mCount = count;
        }

        @Override
        protected void pending(BaseDownloadTask task, int soFarBytes, int totalBytes) {
            Logger.t(TAG).w("pending task name %s", task.getFilename());
        }

        @Override
        protected void progress(BaseDownloadTask task, int soFarBytes, int totalBytes) {
            Logger.t(TAG).i("progress task name %s", task.getFilename());
        }

        @Override
        protected void completed(BaseDownloadTask task) {
            Logger.t(TAG).i("completed task name %s", task.getFilename());
            /**
             * 下载图片，判断如果图片资源全部加载完成，那么继续执行获取菜品数据的接口
             */
            if (initPanel!=null) {
                initPanel.onLoadingDesignBGImageProcess(mCount, task.getFilename());
            }
        }

        @Override
        protected void paused(BaseDownloadTask task, int soFarBytes, int totalBytes) {
            Logger.t(TAG).w("paused task name %s", task.getFilename());
        }

        @Override
        protected void error(BaseDownloadTask task, Throwable e) {
            Logger.t(TAG).e("error task name %s  err msg: %s", task.getFilename(), e.getMessage());
        }

        @Override
        protected void warn(BaseDownloadTask task) {
            Logger.t(TAG).w("warn task name %s", task.getFilename());
        }
    }

    private class InitLoadingSimpleTarget extends SimpleTarget<File> {
        private int mTotal;

        public InitLoadingSimpleTarget(int total) {
            Log.d("initData","total="+total);
            this.mTotal = total;
        }

        @Override
        public void onResourceReady(File file, GlideAnimation<? super File> glideAnimation) {
            /**
             * 下载图片，判断如果图片资源全部加载完成，那么继续执行获取菜品数据的接口
             */
            if (initPanel!=null) {
                initPanel.onLoadingDesignBGImageProcess(mTotal, file.getAbsolutePath());
            }
        }
    }
    private void memCacheDishData(String cacheData) {
        Gson gson = new Gson();
        final DishesTypeDetailEntity entity = gson.fromJson(cacheData, DishesTypeDetailEntity.class);
        if (ObjectUtil.checkObject(entity)) {
            if (entity.resultType == 1) {

                if (ObjectUtil.checkObjectList(entity.Videos)) {
                    //分类视频数据
                    VideoHolder holder = VideoHolder.getInstance();
                    for (VideoModel model : entity.Videos) {
                        holder.put(model.getTypeGUID(), model);
                    }
                }

                if (ObjectUtil.checkObjectList(entity.DishesTypeDetail)) {
                    Executors.newSingleThreadExecutor().execute(new Runnable() {
                        @Override
                        public void run() {
                            DishHolder holder = DishHolder.getInstance();
                            DishTypeHolder typeHolder = DishTypeHolder.getInstance();
                            DishConfHolder confHolder = DishConfHolder.getInstance();
                            typeHolder.types = entity.DishesTypeDetail;
                            if (ObjectUtil.checkObjectList(entity.DishesTypeDetail)) {
                                for (DishesType type : entity.DishesTypeDetail) {
                                    typeHolder.put(type.getTypeGuid(), type);
                                    if (ObjectUtil.checkObjectList(type.getDishes())) {
                                        for (Dish dish : type.getDishes()) {
                                            dish.dish_type_guid = type.getTypeGuid();
                                            holder.put(dish.getDish_guid(), dish);

                                            //脆鱼版本缓存数据
                                            if (TextUtils.isEmpty(dish.getTxt1())) continue;
                                            if (confHolder.containsKey(dish.getTxt1())) {
                                                confHolder.get(dish.getTxt1()).add(dish);
                                            } else {
                                                List<Dish> dishes = new ArrayList<>();
                                                dishes.add(dish);
                                                confHolder.put(dish.getTxt1(), dishes);
                                            }

                                        }
                                    }
                                }
                            }
                        }
                    });
                } else {
                    initPanel.onLoadFail("没有菜品数据");
                }
            } else {
                initPanel.onLoadFail("菜品数据接口访问失败");
            }
        } else {
            initPanel.onLoadFail("菜品数据接口访问失败");
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    public Consumer getError(final  int tag){
        return   new Consumer<Exception>(){

            @Override
            public void accept(@NonNull Exception e) throws Exception {
                if(tag==1){
                    Log.d("initData","getAllDish");
                    File jsonFile = new File(Const.cacheBaseUrl + File.separator + Const.DISH_CACHE_FILE_NAME);
                    String cacheStr = StringFileUtil.readFromFile(jsonFile);
                    boolean isExist = !TextUtils.isEmpty(cacheStr);
                    if (isExist){
                        SPUtils.setAllDish(cacheStr);
                        if (initPanel != null) initPanel.onDishDataErrUseCacheData();
                    } else {
                        if (initPanel != null) initPanel.onInitDishDataFail();
                    }
                }else if(tag==2){
                    Log.d("initData","getDesignData");
                    File jsonFile = new File(Const.cacheBaseUrl + File.separator + Const.DISIGN_CACHE_FILE_NAME);
                    String cacheStr = StringFileUtil.readFromFile(jsonFile);
                    boolean isExist = !TextUtils.isEmpty(cacheStr);
                    if (isExist){
                        SPUtils.setDesign(cacheStr);
                        if (initPanel != null) initPanel.onDesignDataErrUseCacheData();
                    } else {
                        if (initPanel != null) initPanel.onInitDesignDataFail();
                    }
                }else if(tag==3){
                    Log.d("initData","getSallOutData");
                    File jsonFile = new File(Const.cacheBaseUrl + File.separator + Const.SALLOUT_CACHE);
                    String cacheStr = StringFileUtil.readFromFile(jsonFile);
                    boolean isExist = !TextUtils.isEmpty(cacheStr);
//                    boolean isExist = !TextUtils.isEmpty(SPUtils.getSallOutData());
                    if (isExist){
                        SPUtils.setSallOutData(cacheStr);
                        if (initPanel != null) initPanel.onSallOutDataErrUseCache();
                    } else {
                        if (initPanel != null) initPanel.onSallOutDataInitFail();
                    }
                }
                if(e!=null){
                    ViewUtil.LongToast(BaseApplication.context,e.getMessage());
                }else{
                    ViewUtil.ShortToast(BaseApplication.context,"服务器和网络,心情有点差");
                }
            }
        };
    }


    private boolean getDishCache(){
        File jsonFile = new File(Const.cacheBaseUrl + File.separator + Const.DISH_CACHE_FILE_NAME);
        String cacheStr = StringFileUtil.readFromFile(jsonFile);
        SPUtils.setAllDish(cacheStr);
        boolean isExist = !TextUtils.isEmpty(cacheStr);
        return isExist;
    }
    private boolean getDesignCache(){
        File jsonFile = new File(Const.cacheBaseUrl + File.separator + Const.DISIGN_CACHE_FILE_NAME);
        String cacheStr = StringFileUtil.readFromFile(jsonFile);
        SPUtils.setDesign(cacheStr);
        boolean isExist = !TextUtils.isEmpty(cacheStr);
        return isExist;
    }

}
